package com.example.app;

import com.example.service.MyService;
import com.google.common.collect.Lists;
import org.flowable.engine.ManagementService;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.idm.api.User;
import org.flowable.ui.common.model.GroupRepresentation;
import org.flowable.ui.common.model.ResultListDataRepresentation;
import org.flowable.ui.common.model.UserRepresentation;
import org.flowable.ui.common.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* @description
* @author        庞留杰
* @date          2020/9/10 10:29
* @version       V1.0
**/
@RestController
@RequestMapping("/app")
public class RemoteAccountResource {

    @Autowired
    MyService myService;
    @Autowired
    protected IdmIdentityService idmIdentityService;
    @Autowired
    protected ManagementService managementService;

    /**
    * 功能描述: 查询当前用户信息
    * @author: 庞留杰
    * @exception
    * @date: 2020/9/10 10:30
    */
    @GetMapping(value = "/rest/account", produces = "application/json")
    public UserRepresentation getAccount() {
//        RemoteUser remoteUser= new RemoteUser();
//        remoteUser.setFirstName("庞");
//        remoteUser.setLastName("留杰");
//        remoteUser.setFullName("庞留杰");
//        remoteUser.setEmail("182232*****@qq.com");
//        remoteUser.setId("pangliujie");
        User remoteUser = SecurityUtils.getCurrentUserObject();
        //构建用户代表类
        UserRepresentation userRepresentation = new UserRepresentation(remoteUser);
        SecurityUtils.assumeUser(remoteUser); //保证创建流程可用
        return userRepresentation;
    }


    /**
    * 功能描述: 用于Flowable Modeler分组下拉
    * @author: 庞留杰
    * @exception
    * @date: 2020/9/9 17:01
    */
    @RequestMapping(value = "/rest/editor-groups", method = RequestMethod.GET)
    public ResultListDataRepresentation getGroups(@RequestParam(required = false, value = "filter") String filter) {
         /* 查询FLowable自带表act_id_user
            if (StringUtils.isNotBlank(filter)) {
                filter = filter.trim();
                String sql = "select * from act_id_group where NAME_ like #{name}";
                filter = "%" + filter + "%";
                List<Group> groups = idmIdentityService.createNativeGroupQuery().sql(sql).parameter("name", filter).listPage(0, 10);
                List<GroupRepresentation> result = new ArrayList<>();
                for (Group group : groups) {
                    result.add(new GroupRepresentation(group));
                }
                return new ResultListDataRepresentation(result);
            }
            return null;
        */
        // 此处重写
        List<Map<String, Object>> roles = myService.findRoles(filter);
        List<GroupRepresentation> result = new ArrayList();
        for (Map group: roles) {
            GroupRepresentation groupRepresentation = new GroupRepresentation();
            groupRepresentation.setId(group.get("id")+"");
            groupRepresentation.setName(group.get("role_name")+"");
            groupRepresentation.setType(null);
            result.add(groupRepresentation);
        }
        return new ResultListDataRepresentation(result);
    }


    /**
     * 功能描述: 用于Flowable Modeler用户下拉
     * @author: 庞留杰
     * @exception
     * @date: 2020/9/9 17:01
     */
    @RequestMapping(value = "/rest/editor-users", method = RequestMethod.GET)
    public ResultListDataRepresentation getUsers(@RequestParam(value = "filter", required = false) String filter) {
       /* 查询FLowable自带表act_id_user
            if (StringUtils.isNotBlank(filter)) {
                filter = filter.trim();
                String sql = "select * from act_id_user where ID_ like #{id} or LAST_ like #{name}";
                filter = "%"+filter+"%";
                List<User> matchingUsers = idmIdentityService.createNativeUserQuery().sql(sql).parameter("id",filter).parameter("name",filter).listPage(0, 10);List<UserRepresentation> userRepresentations = new ArrayList<>(matchingUsers.size());
                for (User user : matchingUsers) {
                    userRepresentations.add(new UserRepresentation(user));
                }
                return new ResultListDataRepresentation(userRepresentations);
            }
            return null;
        */
        // 此处重写
        List<Map<String, Object>> users = myService.findUsersAndRoleIds(filter);
        List<Map<String, Object>> roles = myService.findRoles("");
        List<UserRepresentation> userRepresentations = new ArrayList();
        for (Map user:users) {
            String real_name = user.get("real_name")+"";
            UserRepresentation userRepresentation = new UserRepresentation();
            userRepresentation.setId(user.get("user_id")+"");
            userRepresentation.setFullName(real_name);
            //姓，名
            if(real_name != null && real_name.length() >= 1){
                String firstName=real_name.substring(1,real_name.length());//名字
                String lastName=real_name.substring(0,1);//姓
                userRepresentation.setFirstName(firstName);
                userRepresentation.setLastName(lastName);
            }else {
                userRepresentation.setFirstName("");
                userRepresentation.setLastName("");
            }
            userRepresentation.setEmail(user.get("email")+"");
            List<GroupRepresentation> groups = Lists.newArrayList();
            for(Map role:roles){
                String[] role_ids = (user.get("role_ids") + "").split(",");
                if(Arrays.asList(role_ids).contains(role.get("id")+"")){
                    GroupRepresentation groupRepresentation = new GroupRepresentation();
                    groupRepresentation.setId(role.get("id")+"");
                    groupRepresentation.setName(role.get("role_name")+"");
                    groupRepresentation.setType(null);
                    groups.add(groupRepresentation);
                }
            }
            userRepresentation.setGroups(groups);
            userRepresentations.add(userRepresentation);
        }
        return new ResultListDataRepresentation(userRepresentations);
    }


}
